//
//  LGHeartRateChartView.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/11/7.
//

#import "LGHeartRateChartView.h"
#import "LGScrollView.h"
#define topMargin    viewPix(50)

#define leftMargin   viewPix(35)+iPadMargin(10)

#define lineHeight   viewPix(35)

#define scrollWidth    (Screen_W - viewPix(83))

#define scrollHeight (lineHeight*5+viewPix(20))

@interface LGHeartRateChartView()<UIScrollViewDelegate>

/**   */
@property (nonatomic , strong)UILabel *dayLabel;
/**   */
@property (nonatomic , strong)UILabel *unitLabel;
/**   */
@property (nonatomic , strong)LGScrollView *scrollView;

/**   */
@property (nonatomic , strong)UIButton *heartButton;

/**   */
@property (nonatomic , strong)UILabel *yaxis110;
/**   */
@property (nonatomic , strong)UILabel *yaxis55;

/**   */
@property (nonatomic , strong)UIView *line110;

/**   */
@property (nonatomic , strong)NSArray *dayArray;
/**   */
@property (nonatomic , strong)NSArray *heartArray;
/**   */
@property (nonatomic , assign)NSInteger totalCount;
/**   */
@property (nonatomic , assign)CGFloat itemWidth;
@end

@implementation LGHeartRateChartView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.itemWidth = scrollWidth/7.0;
        [self createSubView];
    }
    return self;
}

-(void)setDataDic:(NSDictionary *)dataDic{
    _dataDic = dataDic;
    if ([dataDic isKindOfClass:[NSDictionary class]] && dataDic.allKeys.count>0) {
        self.totalCount = [dataDic[@"xAxis"] count]>0?[dataDic[@"xAxis"] count]:1;
        NSInteger count = (self.totalCount>7)?7:self.totalCount;
        self.itemWidth = scrollWidth/count;
        CGFloat totalWidth = viewPix(20)+self.itemWidth*self.totalCount;
        self.scrollView.contentSize = CGSizeMake(totalWidth, scrollHeight);
        [self.scrollView setContentOffset:CGPointMake(totalWidth-scrollWidth-viewPix(10), 0)];
        self.dayArray = dataDic[@"xAxis"];
        self.heartArray = dataDic[@"seriesHr"];
    }
}

//创建X轴坐标
-(void)setDayArray:(NSArray *)dayArray{
    _dayArray = dayArray;
    for (NSInteger i=0; i<dayArray.count; i++) {
        NSArray *tempArray = [LGNSString(dayArray[i]) componentsSeparatedByString:@"-"];
        NSString *dayString = [NSString stringWithFormat:@"%@/%@",tempArray[tempArray.count-2],tempArray[tempArray.count-1]];
        UILabel *dayLabel = [UILabel lableWithText:dayString colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        dayLabel.frame = CGRectMake(viewPix(10)+self.itemWidth*i, lineHeight*4.5, self.itemWidth, lineHeight);
        dayLabel.tag = 1000+i;
        [self.scrollView addSubview:dayLabel];
    }
}

//心率曲线
-(void)setHeartArray:(NSArray *)heartArray{
    _heartArray = heartArray;
    NSMutableArray *pointArray = [NSMutableArray array];
    for (NSInteger i=0; i<heartArray.count; i++) {
        CGFloat pointY = scrollHeight-(([heartArray[i][@"value"] floatValue]-40)/40.0*lineHeight+viewPix(20)+lineHeight*0.5);
        UIButton *button = [UIButton buttonWithImage:@"血压-心率Normal" selectImage:@"血压-心率Select"];
        button.bounds = CGRectMake(0, 0, viewPix(20), viewPix(20));
        button.center = CGPointMake(viewPix(10)+self.itemWidth/2.0+self.itemWidth*i, pointY);
        button.tag = 4000+i;
        [button addTarget:self action:@selector(pointButtonTouch:) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:button];
        NSValue *point = [NSValue valueWithCGPoint:button.center];
        [pointArray addObject:point];
    }
    [self drawCurveLine:pointArray lineColor:@"#D47BDC"];
}

-(void)pointButtonTouch:(UIButton *)sender{
    NSInteger index = sender.tag%1000;
    for(NSInteger i=0; i<self.totalCount; i++){
        UIButton *highBtn = [self viewWithTag:2000+i];
        UIButton *lowBtn = [self viewWithTag:3000+i];
        UIButton *heartBtn = [self viewWithTag:4000+i];
        highBtn.selected = (index == i)?YES:NO;
        lowBtn.selected = (index == i)?YES:NO;
        heartBtn.selected = (index == i)?YES:NO;
    }
    NSDictionary *heartDic = @{@"title":@"心率",@"score":LGNSString(self.heartArray[index][@"value"]),@"status":LGNSString(self.heartArray[index][@"status"])};
    NSArray *tempArray = @[heartDic];

    CGPoint point = [self.scrollView convertPoint:sender.center toView:self.superview];

    NSLog(@">>>???>>>%f--%f",point.x,point.y);
    if(self.delegate && [self.delegate respondsToSelector:@selector(showAlertView:date:point:)]){
        [self.delegate showAlertView:tempArray date:self.dayArray[index] point:point];
    }
    
    CGPoint point2 = [self.scrollView convertPoint:sender.center toView:self.superview.superview.superview];
    if(self.delegate && [self.delegate respondsToSelector:@selector(showAlertView2:date:point:)]){
        [self.delegate showAlertView2:tempArray date:self.dayArray[index] point:point2];
    }
}


//画线
-(void)drawCurveLine:(NSArray *)arry lineColor:(NSString *)color{
    if(arry.count == 0) return;
    CGPoint startPoint = [[arry objectAtIndex:0] CGPointValue];
    CGPoint lastPoint;
    UIBezierPath *lineBeizer = [UIBezierPath bezierPath];
    [lineBeizer setLineWidth:2.0];
    [lineBeizer moveToPoint:startPoint];

    for (NSInteger i = 0;i < arry.count;i++ ) {
        if (i <arry.count-1 ) {
            CGPoint nowPoint = [[arry objectAtIndex:i] CGPointValue];
            CGPoint futPoint  = [[arry objectAtIndex:i+1] CGPointValue];
            [lineBeizer addCurveToPoint:futPoint controlPoint1:CGPointMake((nowPoint.x+futPoint.x)/2, nowPoint.y) controlPoint2:CGPointMake((nowPoint.x+futPoint.x)/2, futPoint.y)];
            if (i == arry.count-2) {
                [lineBeizer moveToPoint:futPoint];//添加连线
                lastPoint = futPoint;
            }
        }
    }
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = lineBeizer.CGPath;
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.strokeColor = [UIColor colorWithString:color].CGColor;
    shapeLayer.lineWidth = 2.0;
    [self.scrollView.layer addSublayer:shapeLayer];
    for(NSInteger i=0; i<self.totalCount; i++){
        UIButton *heartBtn = [self viewWithTag:4000+i];
        [self.scrollView bringSubviewToFront:heartBtn];
    }
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if(self.delegate && [self.delegate respondsToSelector:@selector(chartViewTouchesBegan)]){
        [self.delegate chartViewTouchesBegan];
    }
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if(self.delegate && [self.delegate respondsToSelector:@selector(chartViewTouchesBegan)]){
        [self.delegate chartViewTouchesBegan];
    }
}

-(void)createSubView{
    self.backgroundColor = [UIColor clearColor];
    [self addSubview:self.baseView];
    [self addSubview:self.titleBtn];
    [self.baseView addSubview:self.dayLabel];
    [self.baseView addSubview:self.scrollView];
    [self.baseView addSubview:self.unitLabel];
    [self.baseView addSubview:self.heartButton];
    NSArray *titleArray = @[@"160",@"130",@"100",@"70",@"40"];
    for (NSInteger i=0; i<titleArray.count; i++) {
        //Y轴标题
        UILabel *label = [UILabel lableWithText:titleArray[i] colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        label.frame = CGRectMake(0, topMargin+lineHeight*i, leftMargin, lineHeight);
        [self.baseView addSubview:label];
        //虚线
        LGDottedLineView *lineView = [[LGDottedLineView alloc]initWithFrame:CGRectMake(0, lineHeight*i, self.itemWidth*30+viewPix(50), lineHeight)];
        [self.scrollView addSubview:lineView];
    }
    [self.baseView addSubview:self.yaxis110];
    [self.baseView addSubview:self.yaxis55];
    [self.scrollView addSubview:self.line110];
    [self.titleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.baseView.mas_top).offset(12);
        make.left.right.equalTo(self.baseView);
        make.height.equalTo(@(viewPix(40)));
    }];
}



-(UIView *)baseView{
    if(!_baseView){
        _baseView = [[UIView alloc] initWithFrame:CGRectMake(viewPix(16), viewPix(2), Screen_W-viewPix(32), scrollHeight+topMargin+viewPix(30))];
        _baseView.backgroundColor = [UIColor whiteColor];
        _baseView.cornerRidus = 10;
    }
    return _baseView;
}

-(UIButton *)titleBtn{
    if(!_titleBtn){
        _titleBtn = [UIButton buttonWithTitle:@"心率" titleFont:LGFontWeight(16, UIFontWeightMedium) textColor:@"#282828" frame:CGRectMake(0, kMinY(self.baseView.frame), Screen_W-viewPix(32), viewPix(40))];
        _titleBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _titleBtn.titleEdgeInsets = UIEdgeInsetsMake(0, viewPix(12), 0, 0);
        _titleBtn.backgroundColor = [UIColor whiteColor];
        _titleBtn.cornerRidus = 10;
        _titleBtn.hidden = YES;
        UIImageView *tipView = [[UIImageView alloc]initWithFrame:CGRectMake(Screen_W-viewPix(32)-viewPix(28), viewPix(12), viewPix(16), viewPix(16))];
        tipView.image = [UIImage imageNamed:@"grayTip16"];
        [_titleBtn addSubview:tipView];
    }
    return _titleBtn;
}


-(UILabel *)dayLabel{
    if(!_dayLabel){
        _dayLabel = [UILabel lableWithText:@"最近30天心率分布" colorString:@"#333333" textFont:LGFont(16) textAlignment:NSTextAlignmentLeft lines:1];
        _dayLabel.frame = CGRectMake(viewPix(12), viewPix(14), viewPix(200), viewPix(23));
    }
    return _dayLabel;
}

-(LGScrollView *)scrollView{
    if(!_scrollView){
        _scrollView = [[LGScrollView alloc] initWithFrame:CGRectMake(leftMargin, topMargin, scrollWidth, scrollHeight)];
        _scrollView.contentSize = CGSizeMake(self.itemWidth*30+viewPix(20), scrollHeight);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.delegate = self;
    }
    return _scrollView;
}

-(UILabel *)unitLabel{
    if(!_unitLabel){
        _unitLabel = [UILabel lableWithText:@"次/分钟" colorString:@"#666666" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        _unitLabel.frame = CGRectMake(3, topMargin-6, 50, viewPix(17));
    }
    return _unitLabel;
}

-(UILabel *)yaxis110{
    if(!_yaxis110){
        _yaxis110 = [UILabel lableWithText:@"110" colorString:@"#D47BDC" textFont:LGFontWeight(12, UIFontWeightMedium) textAlignment:NSTextAlignmentCenter lines:1];
        _yaxis110.frame = CGRectMake(0, topMargin+lineHeight*1.7, leftMargin, lineHeight);
    }
    return _yaxis110;
}

-(UIView *)line110{
    if(!_line110){
        _line110 = [[UIView alloc] initWithFrame:CGRectMake(0, lineHeight*2.2, self.itemWidth*30+viewPix(50), lineHeight*1.83)];
        _line110.backgroundColor = [UIColor colorWithString:@"#EABDED" alpha:0.3];
        UIView *line = [[UIView alloc]init];
        line.backgroundColor = [UIColor colorWithString:@"#D47BDC"];
        [_line110 addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self.line110);
            make.height.equalTo(@(1));
        }];
    }
    return _line110;
}

-(UILabel *)yaxis55{
    if(!_yaxis55){
        _yaxis55 = [UILabel lableWithText:@"55" colorString:@"#D47BDC" textFont:LGFontWeight(12, UIFontWeightMedium) textAlignment:NSTextAlignmentCenter lines:1];
        _yaxis55.frame = CGRectMake(0, topMargin+lineHeight*3.5, leftMargin, lineHeight);
    }
    return _yaxis55;
}



-(UIButton *)heartButton{
    if(!_heartButton){
        _heartButton = [UIButton buttonWithTitle:@" 心率" titleFont:LGFont(15) textColor:@"#333333" imageName:@"血压-心率"];
        _heartButton.frame = CGRectMake(0, kMaxY(self.scrollView.frame), Screen_W-viewPix(32), viewPix(20));
        _heartButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    }
    return _heartButton;
}

@end
